require 'net/http'
class VideoScraper
	def initialize(url,file)
		@watch_url=url
		@dest_file=file
	end

	def save_video()
		resp=fetch_simple()
		fmt="18"
		video_id=nil
		t=nil
		if resp =~ /swfArgs\s*=\s*(.*);.*/
			arr=$1
			arr.gsub!(":","=>").gsub!("null","\"\"")
			arr=eval(arr)
			video_id=arr["video_id"]
			t=arr["t"]
			if resp =~ /isHDAvailable\s*=\s*(.*);/
				if $1 == "true"
					fmt="22"
				end
			end

		else
			print "Improper content returned. Couldnt find sefArgs"
		end
		if video_id.nil? or t.nil?
			p "Couldnt find Video Id or t"
		else
			p video_id
			p "Will fetch the video now"
			File.open(@dest_file,"w") { |f|
			 f.write(fetch_complex("http://www.youtube.com/get_video?fmt=" << fmt << "&video_id=" << video_id << "&t=" << t))
			}
		end
	end
	def fetch_simple(limit = 10)
		raise ArgumentError, 'HTTP redirect too deep' if limit == 0
		response = Net::HTTP.get_response(URI.parse(@watch_url))
		case response
			when Net::HTTPSuccess     then response.body
			when Net::HTTPRedirection then fetch_simple(response['location'], limit - 1)
		else
        		response.error!
		end
	end

	def fetch_complex(url)
		uri = URI.parse(url)
		response_chunk = Net::HTTP.start(uri.host,uri.port) { |http|
			p url
			http.get2(uri.path + "?" + uri.query)
		}
		
		case response_chunk
			when Net::HTTPSuccess then response_chunk.read_body
			when Net::HTTPRedirection then fetch_complex(response_chunk["location"])
			when Net::HTTPSeeOther then fetch_complex(response_chunk["location"])

		else
			p "Error occured"
			response_chunk["status"]
		end
	end

end
VideoScraper.new(ARGV[0],ARGV[1]).save_video
